import Vue from 'vue'
import { Message } from 'element-ui'
import SocketPlugin from '@/utils/webSocket.js'
import { getPrintTemplate, batchUpdatePrintCount, updatePrintCount } from '@/api/outStorage'
import moment from 'moment'
class PrintWaybill {
  /**
   * @description: 初始化实例属性，保存参数
   *
   */
  constructor(options, cb, printCallback) {
    this.type = options.printData[0].platformType // Sting     必传  平台类型
    this.printType = options.printType // Sting   必传  打印类型（拣货单、其他）
    if (['CAINIAO', 'TB', 'TM'].includes(options.printData[0].platformType)) this.type = 'CAINIAO'
    this.printOriginalData = options.printData // Array     必传  要打印的数据
    this.printData = this._chunk(options.printData, 100) // Array     必传  对要打印的数据进行分组
    this.parcelType = options.parcelType // Sting   选传  哪家快递，比如，EMS、圆通、申通、顺丰等
    this.cb = cb // Function  选传  打印成功后执行的回调
    this.printCallback = printCallback // Function  选传  打印执行的回调
    this.ws = null // Socket实例
    this.printNum = 0 // 打印次数
    this.taskPerformNum = Math.ceil(options.printData.length / 100) // 循环要执行的次数，每次500条
    this.taskNum = 0 // 给打印机下发打印任务次数
    this.taskSum = 0 // 给打印机下发的任务总数
    this.prinTaskCount = 0 // 给打印机下发的每组任务数
    this.defaultPrinter = '' // 打印机名
    this.prinFinish = false // 打印是否结束
    this.custom = 'http://cloudprint.cainiao.com/template/customArea/14012516/7' // 自定义模板地址
    this.standard = 'http://cloudprint.cainiao.com/template/standard/345208/4' // 标准模板地址
    this.codes = [] // 发货单号，打印成功后增加打印次数使用
    // 平台类型对应的webSocket端口
    this.platformType = {
      CAINIAO: 'ws://localhost:13528', // 菜鸟
      JD: 'ws://localhost:9113', // 京东
      PDD: 'ws://localhost:5000', // 拼多多
      DY: 'ws://localhost:13888', // 抖音
      KS: 'ws://localhost:16888/ks/printer' // 快手
    }
  }

  async initSocket() {
    // 初始化
    this.ws = new SocketPlugin({
      url: this.platformType[this.type],
      received: (data) => {
        // 监听服务器返回信息
        if (typeof data === 'object') {
          if (this.prinFinish === false) {
            Message.close()
            Message.error({ message: `无法打印，请打开《${this.type}打印组件》重试！` })
          }
        } else {
          this._receiveMessage(this._msgHandler(data))
        }
      }
    })

    // 获取完模板后再进行打印任务
    // await this._getStandardTpl()
    // await this._getCustomTpl()
    this._getPrinters()
  }
  // 建立连接，并下发获取打印机列表命令
  _getPrinters() {
    let sendData = {
      cmd: 'getPrinters',
      requestID: this._getUUID(8, 10),
      version: '1.0'
    }
    if (this.type === 'JD') {
      sendData = {
        orderType: 'GET_Printers',
        pin: '用户名',
        parameters: {
          tempUrl: '',
          printName: '',
          printData: ''
        }
      }
    }
    this.ws.connect(sendData)
  }
  // 设置打印机配置
  _setPrinterConfig() {
    const sendData = {
      cmd: 'setPrinterConfig',
      requestID: this._getUUID(8, 10),
      version: '1.0',
      printer: {
        name: this.defaultPrinter,
        needTopLogo: false,
        needBottomLogo: false,
        horizontalOffset: this.type === 'PDD' ? 12 : 0.5,
        verticalOffset: 0.7,
        forceNoPageMargins: true,
        autoPageSize: true,
        orientation: 0,
        autoOrientation: false,
        paperSize: {
          width: 100,
          height: 180
        }
      }
    }
    this.ws.sendMsg(sendData)
  }

  // 处理自定义区域数据 - 拼装
  _processingData(waybillData) {
    // 自定义区域要显示的字段
    // const printCustomItems = { 'goodsInfo': [{ 'lable': '商品编码', 'value': 'goodCode' }, { 'lable': '商品名称', 'value': 'goodsName' }, { 'lable': '商品规格', 'value': 'spec' }, { 'lable': '商品数量', 'value': 'quantity' }, { 'lable': '商品条码', 'value': 'goodsBarCode' }], 'otherInfo': [{ 'lable': '备注：', 'value': 'remarks' }, { 'lable': '波次号：', 'value': 'wavePickingCode' }, { 'lable': '打印顺序：', 'value': 'orderNum' }, { 'lable': '订单来源：', 'value': 'sourcePlatformName' }] }
    const printCustomItems = window.BaseUrl.customPrint

    // 自定义区域数据结构
    const customData = {
      data: {},
      templateURL: waybillData.templateUrl || ''
    }
    // 店铺名称
    const shopNick = waybillData.shopNick || ''
    // 多个商品信息集合
    const goodsMain = [shopNick]
    // 自定义区域 - 商品信息
    waybillData.deliveryItemVOList.forEach(goodsItem => {
      const goodsContent = [] // 单个商品信息
      printCustomItems.goodsInfo.forEach(goods => {
        if (goodsItem[goods.value] !== '') {
          if (goods.value === 'quantity') {
            goodsContent.push(`${goodsItem[goods.value]}*${goodsItem.goodsUnitName}`)
          } else {
            goodsContent.push(goodsItem[goods.value])
          }
        }
      })
      goodsMain.push(goodsContent.join(' '))
    })
    customData.data.info = goodsMain.join('，')

    // 自定义区域 - 最底部信息
    printCustomItems.otherInfo.forEach(other => {
      customData.data[other.value] = waybillData[other.value] ? other.lable + waybillData[other.value] : ''
    })
    // 对于抖音平台的特殊处理
    if (this.type === 'DY') {
      const dYcustomData = {
        shopName: customData.data.orderNum,
        productCount: waybillData.distributionNum,
        productInfo: shopNick + ',' + customData.data.info,
        orderId: customData.data.wavePickingCode.split('波次号：')[1],
        remark: customData.data.orderNum
      }
      Object.assign(customData.data, dYcustomData)
    }
    // 对于快手平台的特殊处理
    if (this.type === 'KS') {
      customData['customData'] = customData.data
      delete customData.data
    }
    return customData
  }
  // 菜鸟打印
  _printCAINIAO() {
    for (const item of this.printData[this.taskNum]) {
      // 菜鸟返回的标准模板数据
      const result = item.printData ? JSON.parse(item.printData) : null
      // 组装要打印的数据
      const printObject = {
        cmd: 'print',
        requestID: new Date().getTime(),
        version: '1.0',
        task: {
          taskID: `${this._getUUID(8, 10)}_${item.code}`,
          preview: false,
          printer: this.defaultPrinter,
          notifyMode: 'oneByOne', // oneByOne/allInOne 打印结果通知模式，是逐个document通知还是批量一次通知最终打印结果
          documents: [{
            documentID: item.waybillCode, // 面单号
            contents: [result, this._processingData(item)]
          }]
        }
      }
      this.ws.sendMsg(printObject)
      console.log('菜鸟-即将打印的数据---->', JSON.stringify(printObject))
    }
  }
  // 拼多多打印
  _printPDD() {
    for (const item of this.printData[this.taskNum]) {
      // 拼多多返回的标准模板数据
      const result = item.printData ? JSON.parse(item.printData) : null
      // 自定义打印模板
      // const customData = this._processingData(item)
      // customData.templateURL = 'https://pos-file.pinduoduo.com/express-common-no-cache/common/xmltemplate/isvtemplate_983722ef-01e6-43e3-9f5b-c7e69d73e23c.xml'
      // 打印数据对象
      const printObject = {
        cmd: 'print',
        requestID: String(new Date().getTime()),
        version: '1.0',
        task: {
          taskID: `${this._getUUID(8, 10)}_${item.code}`,
          preview: false,
          printer: this.defaultPrinter,
          documents: [
            {
              documentID: item.waybillCode, // 面单号
              contents: [result, this._processingData(item)]
              // contents: [
              //   {
              //     encryptedData: 'c30e5fed4b713284d754a2bd00c7184e589fd4e54e6438e7572086b963c3eddb422f7f010ffdf6222354182b9f5569f31e47943e4e25c79c87833806d8130ff28af8082d1bb0414a1af2f8a36ae70c26f7929082aff618581fb7c654cf6ffbea740d05699cc0750f4946df834c83ca6c1698cb734cbdea41c5a3912d252956b97b5687b001ee33d2b2bd96a05ed06e03d5e9bc58c874b685acbc58acfde76b34bd9537833357a783f7268005e8facbb52058ceeab556f3f79506b1565cb0f136083444f6cefbe816f744bdcec3782124e13ddf119b88e7df6d74f6080c8ee4a62f14b76086ba87055cf8973810bd0ddbe8133adca398dce7b63f39f4ed317e54e93883cab6e846392defb5a608def6810fece78e11a5ff33fc0b18136bbbb290c03e56dae53928ca1733ee35c92d798b78b3a33b498535890692e5a2079325e2b7071f6d4665c4ef344f709bf237c66a6a1dfccaf8537162dfa949c79f139958c269657cb185506eef1efa92b59037002000fc2edb9292bf323db714005e309c107f58b7109473ec066db000637c23746d62efec1f87fa326103b3d3a537eb3e20e25daa168128b26731c017ad70d15e983e955062d6f34262b50dc711de3b02e1ecb5f9167ca44cd2e7b7569093c8138a01f824bcb14ba16e84d5c456ea980e823d969139ab9535fad9ebf2557e514576d68bd5f3861f68944e478f889100b0f1ae55fca3654e052d1734c8d1c2bff71a9cf545671cf255fb76d7594d711da9028f3a153c9d4871047b65c8b9b3c26cbfca4e97475d0c572e31d4b42164ea964371c45142768acb568e1635f5bcd217d7f53cc7862fb60c9ad79dd9fda58ed2e65a12b4f2517ab38b42208ca613fcb6a2c4c8fd44f0c9cce7ac6cf8d047a69e368f4d42ead4289e13f272eff4033141a264201aeb6ea6d166ad6ba9ab7e679411808a833e22d99ca4f322e90e8b1d436754768a7c77dbc1be21047806b2370ce6af36b602bcc4030816a5b41a0b2470b1b9c92dddffcad83b91351ce911a60eaa180c6684919194418f908e55d350b9c49827c11590a8e5a540add5a6f5d60dacdbaeb37ac7ec171d17de89f50212e4adb8a67102bf7cb5396fd94ef6d9e7222e003a2dacddb4d115a383b021d7b8dab0a259b5c7108c9938eb5c3ae6b530e01790e0a53196ccdf417adb551e6425a5',
              //     signature: 'DfxAa5VSHg4mOD+AxPxoZBjCr6jRIqu5sMjKZd1QHhAEoaca6F38EVt4Q4lvOJ0ADwwOmytugfhqbzmDDVl+uEEAuTIBGX2K4Clqv5AYLx7yKW7qIvv54kD8364wYcV3JbkvtzaoOqp+ZQ9LaUFrXApnGbPYyn1U6qubAOiNLII=',
              //     templateUrl: 'https://file-link.pinduoduo.com/sdsd_std',
              //     ver: '3'
              //   }
              // ]
            }
          ]
        }
      }
      // printObject.task.documents[0].contents.push(customData)
      this.ws.sendMsg(printObject)
      console.log('拼多多-即将打印的数据---->', JSON.stringify(printObject))
    }
  }
  // 京东打印
  _printJD() {
    for (const item of this.printData[this.taskNum]) {
      // 京东返回的标准模板数据
      const result = item.printData ? JSON.parse(item.printData) : null
      // 组装要打印的数据
      const { data, templateURL: customTempUrl } = this._processingData(item)
      const printObject = {
        orderType: 'PRINT',
        // orderType: 'PRE_View:multi',
        key: item.code,
        parameters: {
          printName: this.defaultPrinter,
          tempUrl: result.templateURL,
          customTempUrl,
          customData: [data],
          printData: [
            result.data
          ]
        }
      }
      this.ws.sendMsg(printObject)
      console.log('京东-即将打印的数据---->', JSON.stringify(printObject))
    }
  }
  // 抖音打印
  _printDY() {
    for (const item of this.printData[this.taskNum]) {
      // 抖音返回的标准模板数据
      const result = item.printData ? JSON.parse(item.printData) : null
      // 组装要打印的数据
      const printObject = {
        cmd: 'print',
        requestID: String(new Date().getTime()),
        version: '1.0',
        task: {
          taskID: `${this._getUUID(8, 10)}_${item.code}`,
          preview: false,
          printer: this.defaultPrinter,
          documents: [{
            documentID: item.waybillCode, // 面单号
            contents: [result, this._processingData(item)]
            // 'contents': [
            //   {
            //     'params': 'access_token=29d07527-6df3-4e05-b410-8dea1adc5fd6&app_key=6995344980931790370&method=logistics.getShopKey&param_json={}&timestamp=1630571823&v=2&sign=b2f8fa8bcc14ac430f3e5ed3f6e015b1',
            //     'signature': 'XF9nKY2uyw9TdbxN6lf434iXwtQ7spDl7E22vf9zW7CKeGPrrdkflcor5+p33Et962+p2UX+fRI9QVqaAbN3to+OXdry8tx2wmTU9lcuUb9cKgW2SHQQW0/ymdoWlJfRkt3jRiEhvS0SyEFB7XUt4Hlbg8hDewy5CzJplWJwU1Yop8q7e9HeNM/S1faWlE7gbc+PIxG34TNae5URpnJFE184uSrXaLMr2aGeUSY9dcokZVRPP3w8sFbEGfRMqC7Oquxs+uiS7KzsbR+nji3C6R9zIi8opBf+Q/kGgyvvNkBJevbaZLxRGwHvi5WlL+YGdYi2hVdNE61tFyF9htqjpQ==',
            //     'encryptedData': '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',
            //     'templateURL': 'https://sf3-ttcdn-tos.pstatp.com/obj/logistics-davinci/template/template_76.xml'
            //   },
            //   {
            //     'data': {
            //       'info': 'ZLMM1 中粮三色藜麦米 1*件 6922510820685',
            //       'remarks': '',
            //       'wavePickingCode': '',
            //       'orderNum': '',
            //       'sourcePlatformName': '订单来源：抖音'
            //     },
            //     'templateURL': 'https://cloudprint.douyinec.com/api/logistics/davinci/template/xml/eVkr1gU3AKq4eDBL2EsQ6Fv40o0ddfIqqXmS90wvWjTCaVza2wpHkVk82mwCQWvhGf8Mc4NVDnUamiXhkTzjMj1tmNQGjmuI6OUK'
            //   }
            // ]
          }]
        }
      }
      this.ws.sendMsg(printObject)
      console.log('抖音-即将打印的数据---->', JSON.stringify(printObject))
    }
  }
  // 快手打印
  _printKS() {
    for (const item of this.printData[this.taskNum]) {
      // 快手返回的标准模板数据
      const result = item.printData ? JSON.parse(item.printData) : null
      // 组装要打印的数据
      const printObject = {
        cmd: 'print',
        requestID: new Date().getTime(),
        version: '1.0',
        task: {
          taskID: `${this._getUUID(8, 10)}_${item.code}`,
          preview: false,
          printer: this.defaultPrinter,
          notifyMode: 'oneByOne', // oneByOne/allInOne 打印结果通知模式，是逐个document通知还是批量一次通知最终打印结果
          documents: [{
            documentID: item.waybillCode, // 面单号
            ksOrderFlag: true,
            contents: [result, this._processingData(item)]
          }]
        }
      }
      this.ws.sendMsg(printObject)
      console.log('快手-即将打印的数据---->', JSON.stringify(printObject))
    }
  }
  // 获取标准模板
  _getStandardTpl() {
    return new Promise((resolve, reject) => {
      getPrintTemplate({ type: 0, code: this.parcelType }).then(res => {
        const data = res.data.filter(item => Number(item.standardWaybillType) === 6)
        this.standard = data[0].standardTemplateUrl
        resolve(data)
      })
    })
  }
  // 获取自定义模板
  _getCustomTpl() {
    return new Promise((resolve, reject) => {
      getPrintTemplate({ type: 1, code: 'zdy' }).then(res => {
        const data = res.data.filter(item => Number(item.standardWaybillType) === 4)
        this.custom = data[0].standardTemplateUrl
        resolve(data)
      })
    })
  }
  // 接收到的消息
  _receiveMessage(result) {
    console.log(`${this.type}打印客户端返回的数据------->`, result)
    if (['CAINIAO', 'PDD', 'DY', 'KS'].includes(this.type)) {
      if (result.cmd === 'getPrinters') {
        this.defaultPrinter = result.defaultPrinter
        this._setPrinterConfig()
      }
      if (result.cmd === 'setPrinterConfig') {
        if (this.type === 'PDD') {
          this._printPDD()
        } else if (this.type === 'DY') {
          this._printDY()
        } else if (this.type === 'KS') {
          this._printKS()
        } else {
          this._printCAINIAO()
        }
      }
      // if (result.cmd === 'print' && result.status === 'success') {
      //   printCount(result.taskID.split('_')[1]) // 面单打印次数
      // }
      if (['notifyPrintResult', 'PrintResultNotify'].includes(result.cmd) && ['rendered', 'printed'].includes(result.taskStatus)) {
        this.codes.push(result.taskID.split('_')[1]) // 面单号/发货单号 集合
        ++this.taskSum
        ++this.prinTaskCount
        const { waybillCode, orderNum } = this.printOriginalData.find((item) => item.code === result.taskID.split('_')[1])
        result.msg = result.printStatus[0].msg
        result.orderNum = orderNum
        result.waybillCode = 'MD' + waybillCode
        result.taskTime = moment().format('YYYY-MM-DD HH:mm:ss:ms')
        this.printCallback && this.printCallback(result)
        if (this.prinTaskCount >= this.printData[this.taskNum].length) {
          this.prinTaskCount = 0
          ++this.taskNum
          if (this.taskNum < this.taskPerformNum) {
            if (this.type === 'PDD') {
              this._printPDD()
            } else if (this.type === 'DY') {
              this._printDY()
            } else {
              this._printCAINIAO()
            }
          }
        }
        if (this.taskSum === this.printOriginalData.length) {
          this.printQuantityAccumulation() // 调用接口累加面单打印次数
          this.prinFinish = true
          this.ws.close()
        }
      }
    } else {
      if (result.code === '6') {
        // 打印机列表
        this.defaultPrinter = result.content.split(',')[0]
        this._printJD()
      }
      if (['2', '9'].includes(result.code)) {
        if (JSON.parse(result.success)) {
          this.codes.push(result.key) // 面单号/发货单号 集合
        }
        ++this.taskSum
        ++this.prinTaskCount
        const { waybillCode, orderNum } = this.printOriginalData.find((item) => item.code === result.key)
        result.taskID = `${result.key}_${result.key}`
        result.orderNum = orderNum
        result.waybillCode = 'MD' + waybillCode
        result.taskTime = moment().format('YYYY-MM-DD HH:mm:ss:ms')
        this.printCallback && this.printCallback(result)
        if (this.prinTaskCount >= this.printData[this.taskNum].length) {
          this.prinTaskCount = 0
          ++this.taskNum
          if (this.taskNum < this.taskPerformNum) {
            this._printJD()
          }
        }
        if (this.taskSum === this.printOriginalData.length) {
          this.printQuantityAccumulation() // 调用接口累加面单打印次数
          this.prinFinish = true
          this.ws.close()
        }
        console.log('京东打印结果--->', result)
        // printCount(result.key) // 面单打印次数
      }
    }
  }
  // 打印次数累计
  printQuantityAccumulation() {
    this.cb && this.cb({ type: 'success', msg: '打印任务成功执行完毕' })
    if (this.printType === 'printPickOrder') {
      // 拣货单累计
      updatePrintCount(this.printOriginalData[0].wavePickingCode)
    } else {
      // 其他打印累计
      if (this.codes.length > 0) {
        batchUpdatePrintCount(this.codes) // 调用接口累加面单打印次数
      }
    }
  }
  // 返回数据格式化
  _msgHandler(msg) {
    if (msg === void 0) {
      return {}
    } else {
      try {
        return JSON.parse(msg)
      } catch (e) {
        return {}
      }
    }
  }
  // 获取请求的UUID，指定长度和进制，如 getUUID(8, 2)   //"01001010" 8 character (base=2)
  _getUUID(len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
    var uuid = []; var i
    radix = radix || chars.length
    if (len) {
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
    } else {
      var r
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
      uuid[14] = '4'
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random() * 16
          uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r]
        }
      }
    }
    return uuid.join('')
  }
  // 把一个数组array按照指定的数组大小size分割成若干个数组块
  _chunk(array, size) {
    let index = 0
    const newArray = []
    while (index < array.length) {
      newArray.push(array.slice(index, index += size))
    }
    return newArray
  }
}
export default PrintWaybill
